/*

 * MainFragment.java
 *
 * Copyright(c) IronOne Technologies (Pvt) Ltd.  All Rights Reserved.
 * This software is the proprietary information of IronOne Technologies (Pvt) Ltd.
 *
 */
package com.ironone.streaming;

import java.util.Arrays;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Response.PagingDirection;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphObject;
import com.facebook.widget.LoginButton;
import com.ironone.streaming.application.CusAlrtBtnTypes;
import com.ironone.streaming.application.CusAlrtIconTypes;
import com.ironone.streaming.application.CustomAlertDialog;
import com.ironone.streaming.application.FormObject;
import com.ironone.streaming.application.MainApplication;
import com.ironone.streaming.exception.ExceptionHandler;
import com.ironone.streaming.lite.R;

/**
 * {This class handles the app and fb login activities}
 * 
 * @Created on Apr 22, 2013 : 1:07:59 PM
 * @author Suren Manawatta
 */
public class MainFragment extends Fragment {
	private UiLifecycleHelper uiHelper;
	private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
	private boolean pendingPublishReauthorization = false;

	Animation rotation;
	ImageView retryButton_circle;
	ImageButton retryButton_flame;
	LinearLayout buttonwraplayout_inner_one;
	LinearLayout buttonwraplayout_inner_two;
	TextView errorTextView;

	@Override
	public void onSaveInstanceState(Bundle outState) {
		try {
			super.onSaveInstanceState(outState);
			outState.putBoolean(PENDING_PUBLISH_KEY, pendingPublishReauthorization);
			uiHelper.onSaveInstanceState(outState);
		} catch (Exception e) {
			// TODO Auto-generated catch block
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		try {
			super.onCreate(savedInstanceState);
			Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(getActivity()));
			uiHelper = new UiLifecycleHelper(getActivity(), callback);
			uiHelper.onCreate(savedInstanceState);
		} catch (Exception e) {
			CustomAlertDialog alertDialog = new CustomAlertDialog(getActivity(), CusAlrtBtnTypes.OK, CusAlrtIconTypes.DUCK);
			alertDialog.setTitleText(getString(R.string.what_the_duck_));
			//alertDialog.setMessageText(getString(R.string.something_snapped));			
			alertDialog.show();
		}
	}

	
	LoginButton fbLoginButton;
	Button btnContinueWithoutInitLogin;
	int inc = 0;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.login, container, false);
		try {
			fbLoginButton = (LoginButton) view.findViewById(R.id.fbLoginButton);
			fbLoginButton.setPublishPermissions(Arrays.asList(new String[]{"user_likes", "user_birthday", "email", "user_location"}));		
			fbLoginButton.setBackgroundResource(R.drawable.facebookloginbutton);
			btnContinueWithoutInitLogin = (Button) view.findViewById(R.id.btnContinueWithoutInitLogin);
						
			/*int scrnWidth = FormObject.getInstance().getScreenWidth();
			int btnWidth = (int)(scrnWidth * 0.65);
			int btnHeight = (int)(btnWidth / 5.6);
			
			if(btnWidth > 354) btnWidth = 354;  // Setting MaxWidth
			if(btnHeight > 62) btnHeight = 62;  // Setting MaxHeight*/
			
			
			
		
			ViewTreeObserver vto = fbLoginButton.getViewTreeObserver();
		    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
		        @Override
		        public void onGlobalLayout() {
		        	if(inc > 3) return;
		        	inc++;
		        	LinearLayout.LayoutParams lParam = (LinearLayout.LayoutParams) fbLoginButton.getLayoutParams();
					int fblb_W = fbLoginButton.getWidth();
					lParam.height = (int)(fblb_W / 5.6);
					lParam.width = fblb_W;
					fbLoginButton.setLayoutParams(lParam);
		            
					btnContinueWithoutInitLogin.setLayoutParams(lParam);
		        }
		    });
			
			/*
			LinearLayout.LayoutParams cParam = (LinearLayout.LayoutParams) btnContinueWithoutInitLogin.getLayoutParams();
			cParam.height = btnHeight;
			cParam.width = btnWidth;
			btnContinueWithoutInitLogin.setLayoutParams(cParam);*/
			
			fbLoginButton.setFragment(this);
			if (savedInstanceState != null) {
				pendingPublishReauthorization = savedInstanceState.getBoolean(PENDING_PUBLISH_KEY, false);
			}

			buttonwraplayout_inner_one = (LinearLayout)view.findViewById(R.id.buttonwraplayout_inner_one);
			buttonwraplayout_inner_two = (LinearLayout)view.findViewById(R.id.buttonwraplayout_inner_two);

			retryButton_flame = (ImageButton) view.findViewById(R.id.retryButton_flame);
			retryButton_circle = (ImageButton) view.findViewById(R.id.retryButton_circle);
			errorTextView = (TextView) view.findViewById(R.id.errorTextView);

			RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) retryButton_flame.getLayoutParams();
			params.width = (int) (FormObject.getInstance().getScreenWidth() / 10);
			params.height = params.width;
			retryButton_flame.setLayoutParams(params);
			retryButton_circle.setLayoutParams(params);

			retryButton_circle = (ImageView) view.findViewById(R.id.retryButton_circle);
			rotation = AnimationUtils.loadAnimation(getActivity(), R.anim.rotate_button);
			rotation.setRepeatCount(Animation.INFINITE);

		} catch (Exception e) {
			CustomAlertDialog alertDialog = new CustomAlertDialog(getActivity(), CusAlrtBtnTypes.OK, CusAlrtIconTypes.DUCK);
			alertDialog.setTitleText(getString(R.string.what_the_duck_));
			//alertDialog.setMessageText(getString(R.string.something_snapped));			
			alertDialog.show();
		}
		return view;
	}


	@Override
	public void onPause() {
		try {
			super.onPause();
			uiHelper.onPause();
			inc = 0;
		} catch (Exception e) {
			CustomAlertDialog alertDialog = new CustomAlertDialog(getActivity(), CusAlrtBtnTypes.OK, CusAlrtIconTypes.DUCK);
			alertDialog.setTitleText(getString(R.string.what_the_duck_));
			//alertDialog.setMessageText(getString(R.string.something_snapped));			
			alertDialog.show();
		}
	}

	@Override
	public void onResume() {
		try {
			super.onResume();
			Session session = Session.getActiveSession();
			if (session != null && (session.isOpened() || session.isClosed())) {
				onSessionStateChange(session, session.getState(), null);
			}
			uiHelper.onResume();
		} catch (Exception e) {
			CustomAlertDialog alertDialog = new CustomAlertDialog(getActivity(), CusAlrtBtnTypes.OK, CusAlrtIconTypes.DUCK);
			alertDialog.setTitleText(getString(R.string.what_the_duck_));
			//alertDialog.setMessageText(getString(R.string.something_snapped));			
			alertDialog.show();
		}
	}


	private Session.StatusCallback callback = new Session.StatusCallback() {
		@Override
		public void call(Session session, SessionState state, Exception exception) {
			onSessionStateChange(session, state, exception);
		}
	};

	private void onSessionStateChange(final Session session, SessionState state, Exception exception) {
		try {
			if (state.isOpened()) {

				if (session.isOpened()) {
					if (pendingPublishReauthorization && state.equals(SessionState.OPENED_TOKEN_UPDATED)) {
						pendingPublishReauthorization = false;
					}

					FormObject.getInstance().setFbLoginStatus(true);
					retryButton_circle.startAnimation(rotation);
					buttonwraplayout_inner_one.setVisibility(View.GONE);
					buttonwraplayout_inner_two.setVisibility(View.VISIBLE);

					new facebookLoginAsync().execute();
				}

			} else if (state.isClosed()) {
				FormObject.getInstance().setFbLoginStatus(false);
				session.closeAndClearTokenInformation();
				retryButton_circle.clearAnimation();
				buttonwraplayout_inner_one.setVisibility(View.VISIBLE);
				buttonwraplayout_inner_two.setVisibility(View.GONE);
			}
		} catch (Exception e) {
			FormObject.getInstance().setFbLoginStatus(false);
			session.closeAndClearTokenInformation();
			retryButton_circle.clearAnimation();
			buttonwraplayout_inner_one.setVisibility(View.VISIBLE);
			buttonwraplayout_inner_two.setVisibility(View.GONE);

			//Toast.makeText(getActivity(), R.string.error_fb_general, Toast.LENGTH_SHORT).show();
			CustomAlertDialog alertDialog = new CustomAlertDialog(getActivity(), CusAlrtBtnTypes.OK, CusAlrtIconTypes.BIRD);
			alertDialog.setTitleText(getString(R.string.pigeon_s_taken_an_arrow));
			//alertDialog.setMessageText(getString(R.string.error_fb_general));
			alertDialog.show();
		}
	}

	Response response0 = null;
	boolean isOneTime = true;
	// Same code can be found on MainApplication's getFacebookProfileData()
	// Too much work to merge these 2 functions
	public class facebookLoginAsync extends AsyncTask<String, Void, Boolean> {

		@Override
		protected Boolean doInBackground(String... arg0) {
			Request request0 = new Request(Session.getActiveSession(), "/me/", null, HttpMethod.GET); 
			response0 = request0.executeAndWait();

			if(response0.getError() != null){
				return false;
			}

			GraphObject go  = response0.getGraphObject();			
			JSONObject jso = go.getInnerJSONObject();
			try {
				FormObject.getInstance().setFbUsername(jso.getString("username"));
				FormObject.getInstance().setFbName(jso.getString("name"));
				FormObject.getInstance().setFbUserId(jso.getString("id"));
				FormObject.getInstance().setFbEmail(jso.getString("email"));
				FormObject.getInstance().setFbBirthday(jso.getString("birthday"));

				JSONObject obj = new JSONObject(jso.getString("location"));
				FormObject.getInstance().setFbLocation(obj.getString("name"));

				FormObject.getInstance().setFbGender(jso.getString("gender"));
			} catch (JSONException e) {
				FormObject.getInstance().setTNLId(null);
			}
			
			StringBuilder sb = new StringBuilder();
			boolean proceed = true;
			String reqURL = "/me/music";

			Request request = new Request(Session.getActiveSession(), reqURL, null, HttpMethod.GET); 
			Response response = request.executeAndWait();
			try {
				JSONArray dataArr = response.getGraphObject().getInnerJSONObject().getJSONArray("data");
				if(dataArr.length() <= 0) proceed = false;
				
				for (int i = 0; i < dataArr.length(); i++) {
					JSONObject json_data = dataArr.getJSONObject(i);
					
					//if (json_data.getString("category").toLowerCase(Locale.ENGLISH).startsWith("radio station")
						//	|| json_data.getString("category").toLowerCase(Locale.ENGLISH).startsWith("musician"))
						sb.append(json_data.getString("name") + R.string.like_separator);
				}
			} catch (JSONException e) {
				proceed = false;
			}
			
			while (proceed) {				
					Request nextPageRequest = response.getRequestForPagedResults(PagingDirection.NEXT);
					response = nextPageRequest.executeAndWait();
					
					try {
						JSONArray dataArr = response.getGraphObject().getInnerJSONObject().getJSONArray("data");
						if(dataArr.length() <= 0) proceed = false;
						
						for (int i = 0; i < dataArr.length(); i++) {
							JSONObject json_data = dataArr.getJSONObject(i);
							
							//if (json_data.getString("category").toLowerCase(Locale.ENGLISH).startsWith("radio")
								//	|| json_data.getString("category").toLowerCase(Locale.ENGLISH).startsWith("musician"))
								sb.append(json_data.getString("name") + R.string.like_separator);
						}
					} catch (JSONException e) {
						proceed = false;
					}
				}
					
			FormObject.getInstance().setFbMusicLiked(sb.toString());
			MainApplication.foSaveChanges(getActivity());
			return true;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);

			if(response0.getError() != null){
				Session.getActiveSession().closeAndClearTokenInformation();
				FormObject.getInstance().setFbLoginStatus(false);

				retryButton_circle.clearAnimation();
				buttonwraplayout_inner_one.setVisibility(View.VISIBLE);
				buttonwraplayout_inner_two.setVisibility(View.GONE);

				String ss = response0.getError().getErrorMessage();
				Toast.makeText(getActivity(), ss, Toast.LENGTH_SHORT).show();
			}
			
			if(result && isOneTime){ // Make sure this runs only once!
				retryButton_circle.clearAnimation();
				Intent intent = new Intent(getActivity(), RadioPlayerActivity.class);
				//getActivity().overridePendingTransition(R.anim.slide_middle_to_left, R.anim.slide_right_to_middle);
				//getActivity().overridePendingTransition(R.animator.activity_translate_anim1,R.animator.activity_translate_anim2);
				MainFragment.this.startActivity(intent);
				getActivity().finish();
				isOneTime = false;
			}
		}
	}



	@Override	
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		uiHelper.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		uiHelper.onDestroy();
	}

	/**private void publishStory() {
	/*private void publishStory() {
		Session session = Session.getActiveSession();
		if (session != null) {
 			Bundle postParams = new Bundle();
			// Check for publish permissions
			// List<String> permissions = session.getPermissions();
			
			 * if (!isSubsetOf(PERMISSIONS, permissions)) {
			 * pendingPublishReauthorization = true;
			 * Session.NewPermissionsRequest newPermissionsRequest = new Session
			 * .NewPermissionsRequest(this, PERMISSIONS);
			 * session.requestNewPublishPermissions(newPermissionsRequest);
			 * return; }
			 

			Bundle postParams = new Bundle();
			postParams.putString("name", "TNL Radio for Android..");
			postParams.putString("caption", "TNLROCKS Goes Where You Go...");
			postParams.putString("description", "TNL RADIO Goes Where You Go...");
			postParams.putString("link", "http://www.tnlradio.com/");
			postParams.putString("picture",
					"https://fbcdn-photos-e-a.akamaihd.net/hphotos-ak-prn1/851561_449456361819307_1194483068_n.png");
			

			Request.Callback callback = new Request.Callback() {
				public void onCompleted(Response response) {
						JSONObject graphResponse = response.getGraphObject().getInnerJSONObject();
					String postId = null;
					try {
						postId = graphResponse.getString("id");
					} catch (JSONException e) {
						Log.i(TAG, "JSON error " + e.getMessage());
					}
					FacebookRequestError error = response.getError();
					if (error != null) {
						Intent i = new Intent(getActivity(), MainActivity.class);
						startActivity(i);
					} else {
					}
				}
			};

			Request request = new Request(session, "me/feed", postParams, HttpMethod.POST, callback);
			RequestAsyncTask task = new RequestAsyncTask(request);
			task.execute();
		}
	}*/
}